//    LunchIT - Tool to make decisions of a lunch restaurant.
//    Copyright (C) 2010 Jukka Hell
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

package fi.hell.lunchit

class Vote {
	
	static belongsTo = [round:Round]
	
	Restaurant restaurant
	Integer vote

    static mapping = {
		sort "vote"
	}

    static constraints = {
		restaurant	(nullable:false)
		vote		(nullable:false, unique:['round','restaurant'], range:1..3)
    }
	
	static Map<Restaurant, Integer> topVotes(int max = 20) {
		List results = Vote.createCriteria().list {
			projections {
				groupProperty("restaurant")
				sum("vote", "voteSum")
			}
			order("voteSum", "desc")
			maxResults(max)
		}

		Map<String, Integer> topVotes = [:]
		for(int i = 0; i < results.size(); i++) {
			topVotes[results[i][0]] = results[i][1]
		}

		return topVotes
	}

    static List<User> restaurantVoters(Restaurant r, Calendar day = null) {
        if (!day) {
            day = Round.today()
        }

		List<User> results = Vote.createCriteria().list {
            round {
                eq("day", day)
            }
            eq("restaurant", r)
			order("vote", "desc")
		}

		return results
	}
}
